package lowijs.XfireClient.util;

import java.io.File;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

import android.os.Environment;
import android.util.Log;

public class Util {
	public static final DateFormat FORMAT = new SimpleDateFormat("MMddHHmmss");

	private static String STORAGE_PATH = null;
	
	/**
	 * Hashes a plain text string with the SHA1 algorithm.
	 * @param plain a plain text string.
	 * @return the hashed string.
	 */
	public static String toSHA1(String plain) {
		try {
			MessageDigest md = MessageDigest.getInstance("SHA1");
			md.update(plain.getBytes());
			byte[] hash = md.digest();
			StringBuffer hexstring = new StringBuffer();
			for (int i = 0; i < hash.length; i++)
				hexstring.append(String.format("%02x", 0xFF & hash[i]));
			
			return hexstring.toString().toLowerCase();
		} catch (NoSuchAlgorithmException nsae) {
			return null;
		}
	}

	public static int findByteArray(byte[] source, byte[] key) {
		int possible = 0, currentKey = 0;
		boolean ontoSomething = false;

		for (int i = 0; i < source.length; i++) {
			if (source[i] == key[currentKey]) {
				if (!ontoSomething) {
					ontoSomething = true;
					possible = i;
				}

				if (++currentKey == key.length) {
					return possible;
				}
			} else if (ontoSomething) {
				ontoSomething = false;
				possible = 0;
				currentKey = 0;
			}
		}

		return -1;
	}

	public static int findByteArray(ByteBuffer source, byte[] key) {
		int possible = 0, currentKey = 0;
		boolean ontoSomething = false;

		source.position(0);
		for (int i = 0; i < source.limit(); i++) {
			if (source.get(i) == key[currentKey]) {
				if (!ontoSomething) {
					ontoSomething = true;
					possible = i;
				}

				if (++currentKey == key.length) {
					return possible;
				}
			} else if (ontoSomething) {
				ontoSomething = false;
				possible = 0;
				currentKey = 0;
			}
		}

		return -1;
	}

	public static int intFromBytes(byte[] data, int off, int len) {
		int result = 0;
		for (int i = 0; i < len; i++) {
			result |= (data[off + i] & 0xFF) << 8 * i;
		}
		return result;
	}
	
	public static long longFromBytes(byte[] data, int off, int len) {
		long result = 0;
		for (int i = 0; i < len; i++) {
			result |= (data[off + i] & 0xFF) << 8 * i;
		}
		return result;
	}

	public static File getFile(String path) {
		if (STORAGE_PATH == null) {
			// Setup storage
			if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
				Util.STORAGE_PATH = null;
				Log.d("Util", "media mounted!");
			} else {
				Util.STORAGE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/xfdroid";
				File dir = new File(Util.STORAGE_PATH);
				dir.mkdirs();
			}
		}

		if (!path.startsWith("/")) {
			path = "/" + path;
		}

		return new File(STORAGE_PATH + path);
	}

	public static String toHex(byte[] buffer, String prefix, int perline) {
		StringBuilder builder = new StringBuilder();
		StringBuilder builder2 = new StringBuilder();
		int len = buffer.length;

		if (len > 120) {
			len = 120;
		}

		for (int i=0, n=len; i<n; i+=perline) {
			String sep = "";
			builder.append(prefix);
			builder.append("[");

			for (int j=i, o=i+perline; j<o && j<len; j++) {
				if (j < buffer.length) {
					char c = (char)(buffer[j]&0xFF);
					String hex = Integer.toHexString(c);

					if (hex.length() < 1) {
						builder.append(sep).append("0").append(hex);
					} else {
						builder.append(sep).append(hex);
					}

					if (c >= 32 && c <= 126) {
						builder2.append((char)c);
					} else {
						builder2.append(".");
					}
				} else {
					builder.append(sep).append("  ");
				}

				sep = " ";
			}

			builder.append("] ").append(builder2);
			builder2.setLength(0);
		}

		return builder.toString();
	}
}
